<template>
  <div class="editinput">
    <div class="editinput-head">
      <div>
        <el-popover
          placement="top"
          :width="470"
          trigger="click"
          :visible="expressionpopoverVisible"
          @show="showPopoverHandler"
          @hide="closePopoverHandler"
        >
          <template #reference>
            <div class="icondiv">
              <div
                class="expressiondiv"
                @click="expressionpopoverVisible = true"
              >
                <img
                  :src="biaoqingimg"
                  alt="表情"
                  style="height: 20px"
                  class="expression"
                />
              </div>
              <div
                class="expressiondiv"
                style="margin-left: 10px"
                @click="clickaddimg"
              >
                <img
                  :src="addimg"
                  alt="添加"
                  style="height: 20px"
                  class="expression"
                />
              </div>
            </div>
          </template>
          <div class="expressioncontent" v-click-outside="onClickOutside">
            <el-scrollbar height="300px">
              <div class="expressioncontentscro">
                <div
                  class="expressioncontent-item"
                  v-for="(value, key) in expressionimg"
                  :key="key"
                  @click="clickexpressionimg(key, value)"
                >
                  <el-image
                    style="width: 80px; height: 80px"
                    :src="value"
                    :fit="fit"
                  />
                </div>
              </div>
            </el-scrollbar>
          </div>
        </el-popover>
      </div>
    </div>
    <el-scrollbar
      style="height: 50%; overflow-x: hidden !important"
      ref="popoverContent"
    >
      <div
        ref="editorRef"
        class="editor"
        contenteditable="true"
        v-html="editorText"
        @click="handleClick"
        @input="handleInput"
        @focus="handleFocus"
        @blur="handleBlur"
        style="user-select: text; -webkit-user-select: text"
      ></div>
    </el-scrollbar>

    <div class="editinput-buttons">
      <el-button class="editinput-button" size="small" @click="clicksubmit"
        >发送</el-button
      >
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive, provide, inject } from "vue";

import { ClickOutside as vClickOutside } from "element-plus";
// import biaoqing from "@/assets/images/biaoqing.png";
// import add from "@/assets/images/add.png";

import { ipc } from "@/utils/ipcRenderer";
import { ipcApiRoute } from "@/api/main.js";

const chatmessagedata = inject<any>("chatmessagedata");
const activeaccount = inject<any>("activeaccount");
const sidexpression = ref("");

const expressionimg = ref({
  s20180806g00101: "https://im.rimg.com.tw/im/sticker/1/1.png",
  s20180806g00102: "https://im.rimg.com.tw/im/sticker/1/2.png",
  s20180806g00103: "https://im.rimg.com.tw/im/sticker/1/3.png",
  s20180806g00104: "https://im.rimg.com.tw/im/sticker/1/4.png",
  s20180806g00105: "https://im.rimg.com.tw/im/sticker/1/5.png",
  s20180806g00106: "https://im.rimg.com.tw/im/sticker/1/6.png",
  s20180806g00107: "https://im.rimg.com.tw/im/sticker/1/7.png",
  s20180806g00108: "https://im.rimg.com.tw/im/sticker/1/8.png",
  s20180806g00109: "https://im.rimg.com.tw/im/sticker/1/9.png",
  s20180806g00110: "https://im.rimg.com.tw/im/sticker/1/10.png",
  s20180806g00111: "https://im.rimg.com.tw/im/sticker/1/11.png",
  s20180806g00112: "https://im.rimg.com.tw/im/sticker/1/12.png",
  s20180806g00113: "https://im.rimg.com.tw/im/sticker/1/13.png",
  s20180806g00114: "https://im.rimg.com.tw/im/sticker/1/14.png",
  s20180806g00115: "https://im.rimg.com.tw/im/sticker/1/15.png",
  s20180806g00116: "https://im.rimg.com.tw/im/sticker/1/16.png",
  s20180806g00117: "https://im.rimg.com.tw/im/sticker/1/17.png",
  s20180806g00118: "https://im.rimg.com.tw/im/sticker/1/18.png",
  s20180806g00119: "https://im.rimg.com.tw/im/sticker/1/19.png",
  s20180806g00120: "https://im.rimg.com.tw/im/sticker/1/20.png",
});

const biaoqingimg = ref(
  "data:image/svg+xml;charset=utf-8,%3Csvg width='25' height='25' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Ccircle stroke='%239B9B9B' stroke-width='1.8' cx='12.5' cy='12.5' r='11.6'/%3E%3Ccircle fill='%239B9B9B' cx='8.036' cy='10.714' r='1.786'/%3E%3Ccircle fill='%239B9B9B' cx='16.964' cy='10.714' r='1.786'/%3E%3Cpath d='M8.929 16.964c2.645 2.381 5.026 2.381 7.142 0' stroke='%239B9B9B' stroke-width='1.8' stroke-linecap='round'/%3E%3C/g%3E%3C/svg%3E"
);
const addimg = ref(
  "data:image/svg+xml,%3Csvg%20width%3D'25'%20height%3D'25'%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%3E%3Cg%20stroke%3D'%239B9B9B'%20stroke-width%3D'1.8'%20fill%3D'none'%20fill-rule%3D'evenodd'%3E%3Ccircle%20cx%3D'12.5'%20cy%3D'12.5'%20r%3D'11.6'%2F%3E%3Cpath%20d%3D'M7.143%2012.5h10.714M12.5%207.143v10.714'%20stroke-linecap%3D'round'%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E"
);

const editorRef = ref(null);
const messagedata = reactive({
  editorText: "",
  type: "text",
  isChange: true,
  // 记录光标最后位置
  lastCursor: null,
});

const expressionpopoverVisible = ref(false);

const handleClick = () => {
  messagedata.lastCursor = getLastCursor();
};

// 获取光标最后位置
const getLastCursor = () => {
  let sel = window.getSelection();
  if (sel && sel.rangeCount > 0) {
    return sel.getRangeAt(0);
  }
};

const handleInput = () => {
  messagedata.lastCursor = getLastCursor();
};

const stripHtmlTags = (html) => {
  return html.replace(/<[^>]*>?/gm, '');
}

const clicksubmit = () => {
  if (editorRef.value.innerHTML != "") {
    let editorhtml = editorRef.value.innerHTML;
    if (editorhtml.startsWith("<img")) {
      let regex = /src="([^"]*)"/;
      let match = editorhtml.match(regex);
      if (match) {
        let srcValue = match[1]; // 第一个捕获组中的内容即为 src 属性的值
        if (srcValue.startsWith("http")) {
          messagedata.type = "sticker";
          messagedata.editorText = srcValue;
        } else {
          messagedata.type = "base64";
          // console.log(srcValue);
          // messagedata.editorText = srcValue.substring(srcValue.indexOf(',') + 1);;
          messagedata.editorText = srcValue;
        }
      }
    } else {
      messagedata.type = "text";
      messagedata.editorText = stripHtmlTags(editorhtml);
    }

    let data = {
      to: chatmessagedata.value.id,
      userid: activeaccount.value.bid_rid,
      cookie: activeaccount.value.cookie,
      type: messagedata.type,
      msg: messagedata.editorText,
      sid: "",
    };

    if (data.type == "sticker") {
      data.msg = "傳送一張可愛貼圖";
      data.sid = sidexpression.value;
    }
    // console.log(data);

    ipc.invoke(ipcApiRoute.sendmessage, data).then((res) => {
      if (res == 201) {
        // console.log("发送成功");
        editorRef.value.innerHTML = "";
      }
    });
  }
};

const clickexpressionimg = (key, value) => {
  sidexpression.value = key;
  expressionpopoverVisible.value = false;
  editorRef.value.innerHTML = `<img src="${value}"/>`;
};

const showPopoverHandler = () => {
  expressionpopoverVisible.value = true;
};
const closePopoverHandler = () => {
  expressionpopoverVisible.value = false;
};
const onClickOutside = () => {
  expressionpopoverVisible.value = false;
};

const clickaddimg = () => {
  ipc.invoke(ipcApiRoute.selectimg).then((res) => {
    if (res != '') {
      editorRef.value.innerHTML = `<img src="${res}" alt="">`
    }
    
  });
};
</script>

<style scoped>
.editinput {
  width: 98%;
  height: 100%;
  overflow-x: hidden !important;
}
.editinput-head {
  height: 20%;
  padding-left: 10px;
  display: flex;
  justify-items: flex-start;
  align-items: center;
}

.editor {
  height: 100%;
  width: calc(97% - 20px);
  border: none;
  overflow-x: hidden !important;
  padding: 10px;
  text-align: left; /* 确保文本和光标靠左对齐 */
  word-break: break-word;
  font-size: 14px;
  outline: none;
}

.editinput-buttons {
  height: 30%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.editinput-button {
  width: 15%;
  min-width: 80px;
  height: 70%;
  color: red;
  border: none;
  background-color: #f2f3f5;
}
.editinput-button:hover {
  background-color: #f2f3f5;
}
.expressiondiv {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
}
.expression {
  height: 25px;
  cursor: pointer;
}

.expressioncontentscro {
  display: flex;
  flex-wrap: wrap;
}
.expressioncontent-item {
  padding: 5px 15px;
  cursor: pointer;
}

.icondiv {
  display: flex;
  align-items: center;
}
</style>

<style>
.editor img {
  width: 120px;
}
</style>